package de.hhbk.feedbackmodul.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.hhbk.feedbackmodul.beans.applicationscope.ApplicationManagerBean;
import de.hhbk.feedbackmodul.beans.sessionscope.SessionManagerBean;
import de.hhbk.feedbackmodul.entities.User;


public class AuthenticationFilter implements Filter {

	private FilterConfig fc;
	
	public void destroy() {
		
	}


	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		boolean ignore = false;
		if(fc.getInitParameter("ignoredTargets") != null)
		{
 			String[] ignoredTargets;
 			ignoredTargets = fc.getInitParameter("ignoredTargets").split(",");
 			for(String s : ignoredTargets)
 			{
 				if(((HttpServletRequest) request).getServletPath().contains(s))
 				{
 					ignore = true;
 				}
 			}
		}
 		if(!ignore)
 		{
			SessionManagerBean sessionBean = (SessionManagerBean) ((HttpServletRequest) request).getSession().getAttribute("sessionManagerBean");
			ApplicationManagerBean masterBean = (ApplicationManagerBean) fc.getServletContext().getAttribute("applicationManagerBean");
			if(sessionBean != null)
			{
				if(sessionBean.getUserinfo() != null)
				{
					User user = null;
					for(User u : masterBean.getUserlist())
					{
						if(u.getId().equals(sessionBean.getUserinfo().getLoginName()))
						{
							if(u.getPasswort().equals(sessionBean.getUserinfo().getLoginPasswort()))
							{
								user = u;
								sessionBean.getUserinfo().setUser(u);
							}
						}
					}
					if(user == null)
					{
						((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/index.jsp");
					}
				}
				else
				{
					((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/index.jsp");
				}
			}
			else
			{
				((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/index.jsp");
			}
 		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		fc = fConfig;
	}

}
